export const requestIdleCallback = (callback) => {
	var startTime = Date.now();
	return setTimeout(function () {
		callback({
			didTimeout: true,
			timeRemaining: function () {
				return Math.max(0, 50 - (Date.now() - startTime));
			},
		});
	}, 0);
};

if (!window.requestIdleCallback) {
	window.requestIdleCallback = requestIdleCallback;
}

class Events {
	constructor() {
		this.events = new Map();
	}
	on(type, fn) {
		this.events.set(fn, type);
	}
	off(type, fn) {
		if (type && !fn) {
			this.events.entries().forEach((item) => {
				if (type == item[1]) {
					this.events.delete(item[0]);
				}
			});
			return;
		}
		this.events.delete(fn);
	}
	emit(type, val) {
		this.events.entries().forEach((item) => {
			if (type == item[1]) {
				item[0](val);
			}
		});
	}
}

export const subscribe = new Events();

export const sleep = (timer) => {
	//* 任务分片执行
	let time = null;
	return new Promise((resolve) => {
		if (time) {
			clearTimeout(time);
		}
		time = setTimeout(() => {
			resolve(true);
		}, timer);
	});
};

export const debounce = (fn, delay = 500) => {
	let timer = null;
	return function () {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			fn.apply(this, arguments);
			timer = null;
		}, delay);
	};
};

//* 优化多任务
export const mixinsDefer = {
	data() {
		return {
			deferCount: 1,
		};
	},
	methods: {
		renderDefer(maxCount = 100) {
			let id = null;
			const updateFrameCount = () => {
				id = requestAnimationFrame(() => {
					this.deferCount += 10;
					if (this.deferCount >= maxCount) {
						return;
					}
					updateFrameCount();
				});
			};
			updateFrameCount();
			return {
				defer: (n) => {
					return this.deferCount >= n;
				},
				clearDefer: () => {
					id && cancelAnimationFrame(id);
				},
			};
		},
	},
};

export const renderDefer = (maxCount = 500) => {
	let deferCount = 1;
	let id = null;
	function updateFrameCOunt() {
		id = requestAnimationFrame(() => {
			deferCount++;
			if (deferCount >= maxCount) {
				return;
			}
			updateFrameCOunt();
		});
	}
	updateFrameCOunt();
	return {
		defer: function (n) {
			console.log(deferCount >= n, "defer", deferCount, n);
			return deferCount >= n;
		},
		clearDefer: function () {
			id && cancelAnimationFrame(id);
		},
	};
};
